/*
 * @Description:
 * @Version: 2.0
 * @Author: Mason
 * @Date: 2023-10-14 16:29:35
 * @LastEditors: Mason
 * @LastEditTime: 2023-10-18 22:37:25
 */
package handler

import (
	"net/http"
	"time"

	"gitee.com/cy1113/credits/dao"
	"gitee.com/cy1113/credits/model"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type User struct{}

func (u User) Create(c *gin.Context) {

	var obj struct {
		Username string `json:"username"`
		Phone    string `json:"phone"`
	}

	err := c.BindJSON(&obj)
	if err != nil {
		logrus.Errorf("error to bind json %s", err)
		c.JSON(http.StatusBadRequest, model.ErrResult("参数错误"))
		return
	}

	err = dao.User.Create(&model.User{
		Id:       primitive.NewObjectID(),
		Username: obj.Username,
		Phone:    obj.Phone,
		CreateAt: time.Now(),
	})

	if err != nil {
		logrus.Errorf("error to create user: %s", err)
		c.JSON(http.StatusInternalServerError, model.ErrResult("系统错误"))
		return
	}

	c.JSON(http.StatusOK, model.SuccessResult("success"))
}

func (u User) FindOne(c *gin.Context) {
	username := c.Query("username")
	user, err := dao.User.Find(username)
	if err != nil {
		logrus.Errorf("error to query user: %s, %s", username, err)
		c.JSON(http.StatusBadRequest, model.ErrResult("参数错误"))
		return
	}
	c.JSON(http.StatusOK, model.SuccessResult("success").WithData(user))
}
